//
//  LingQuPosController.m
//  PosApp
//
//  Created by 刘萍 on 2018/9/10.
//  Copyright © 2018年 李英新. All rights reserved.
//

#import "LingQuPosController.h"

#import "MyAddressController.h"
#import "DYLQSuccessVC.h"
#import "DYLQFiledVC.h"
#import "RouterManager.h"
#import "PPNumberButton.h"


@interface LingQuPosController ()<MyAddressControllerDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TopHeadViewH;
@property (weak, nonatomic) IBOutlet UIView *LQBackView;
@property (weak, nonatomic) IBOutlet UIView *AddressView01;
@property (weak, nonatomic) IBOutlet UIView *AddressView02;
@property (strong, nonatomic) IBOutlet UILabel *AddressName;
@property (strong, nonatomic) IBOutlet UILabel *AddressiPhone;
@property (strong, nonatomic) IBOutlet UILabel *AddressLabel;
@property (weak, nonatomic) IBOutlet UIView *VQuanContainer;


@property (weak, nonatomic) IBOutlet UIImageView *PosImage;
@property (weak, nonatomic) IBOutlet UILabel *PosLabel01;
@property (weak, nonatomic) IBOutlet UILabel *MDLabel;

@property (weak, nonatomic) IBOutlet UILabel *PosLabel02;
@property (weak, nonatomic) IBOutlet UILabel *PosLabel03;
@property (weak, nonatomic) IBOutlet UILabel *PriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *PosYJPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *YFPriceLabel;
@property (weak, nonatomic) IBOutlet UIView *ChangeView;
@property (weak, nonatomic) IBOutlet UILabel *PosNumbLabel;
@property (weak, nonatomic) IBOutlet UILabel *AllPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *PayTypeBtn;
@property (strong, nonatomic) MBProgressHUD * hud;
@property (strong, nonatomic) NSString * AddressID;
@property (assign, nonatomic) NSUInteger numb;
@property (weak, nonatomic) IBOutlet UIView *VPPButtonContainer;
@property (strong, nonatomic)PPNumberButton * numberButton;
@property (weak, nonatomic) IBOutlet UILabel *LBLQuanLeft;
@property (copy, nonatomic)NSString * quanNum;//使用抵用券的数量
@property (assign, nonatomic)NSInteger  maxQuanNum;//最大使用抵用券的数量
@end

@implementation LingQuPosController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UINavigationBar appearance].backIndicatorImage = [UIImage imageNamed:@"icon_arrowback_n"];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.quanNum = @"0";
    self.maxQuanNum = 0;
    
    [RouterManager fetchQuan:^(NSInteger maxCount) {
        self.maxQuanNum = maxCount;
        self.LBLQuanLeft.text = [NSString stringWithFormat:@"(机器抵用券剩余%ld张)",(long)self.maxQuanNum];
        self.numberButton.maxValue =  MIN(self.maxQuanNum, self.numb);;

    }];
    
    if([self.Model.pos_deduction  isEqual: @"1"]){
        self.VQuanContainer.hidden = NO;
    }else{
        self.VQuanContainer.hidden = YES;
    }
    
    

    
    ///初始化ppbutton
    PPNumberButton *numberButton = [PPNumberButton numberButtonWithFrame:CGRectMake(20, 0, 90, 30)];
    //设置边框颜色
    numberButton.borderColor = [UIColor grayColor];
    numberButton.increaseTitle = @"＋";
    numberButton.decreaseTitle = @"－";
    numberButton.currentNumber = 0;
    numberButton.maxValue =  MIN(self.maxQuanNum, self.numb);;
    
    self.numberButton = numberButton;
    numberButton.resultBlock = ^(PPNumberButton *ppBtn,CGFloat number, BOOL increaseStatus){
        
        self.quanNum = [NSString stringWithFormat: @"%.0f",number];
        NSLog(@"%@",self.quanNum);
        
        float res = ([self.Model.pos_price_deposit floatValue] + [self.Model.pos_price floatValue]) * (self.numb - [self.quanNum floatValue]) + [self.Model.pos_price_freight floatValue];
        
       self.AllPriceLabel.text =  [NSString stringWithFormat:@"%.2f",res];
    };
    [self.VPPButtonContainer addSubview:numberButton];
    
    
    
    
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"商品详情";
    self.numb = 1;
    UIButton * leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [leftBtn setImage:[UIImage imageNamed:@"MainBackImage_W"] forState:UIControlStateNormal];
    leftBtn.imageEdgeInsets = UIEdgeInsetsMake(5,0,5,20);
    [leftBtn addTarget:self action:@selector(ClickLeftBarButtonItem) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,KScreenW,KScreenH/2);
    gl.startPoint = CGPointMake(0, 0);
    gl.endPoint = CGPointMake(1, 1);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:255/255.0 green:109/255.0 blue:1/255.0 alpha:1].CGColor,(__bridge id)[UIColor colorWithRed:251/255.0 green:41/255.0 blue:67/255.0 alpha:1].CGColor];
    gl.locations = @[@(0.0),@(1.0f)];
    [self.LQBackView.layer addSublayer:gl];
    
    
    
    UITapGestureRecognizer * AddTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ClickOnBtnToLookLocationController)];
    [self.AddressView01 addGestureRecognizer:AddTap];
    [self.AddressView02 addGestureRecognizer:AddTap];
    
    
    //阴影颜色
    self.PriceLabel.shadowColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:0.82];
    //阴影偏移  x，y为正表示向右下偏移
    self.PriceLabel.shadowOffset = CGSizeMake(1, 1);
    
    self.ChangeView.layer.cornerRadius = 4;
    self.ChangeView.layer.borderColor = KRGBColor(243, 243, 243).CGColor;
    self.ChangeView.layer.borderWidth = 1;
    
    [self.PayTypeBtn setImage:[UIImage imageNamed:@"XFChooseImage_None"] forState:UIControlStateNormal];
    [self.PayTypeBtn setImage:[UIImage imageNamed:@"XFChooseImage_Select"] forState:UIControlStateSelected];
    self.PayTypeBtn.selected = YES;
    
    [self.PosImage sd_setImageWithURL:[NSURL URLWithString:self.Model.pos_pic] placeholderImage:[UIImage imageNamed:@"MainZWImage"]];
    NSString * str = @"%";
    if ([self.Model.pos_three isEqual:@"1"]) {
        self.PosLabel01.text = [NSString stringWithFormat:@"%@%@+3元/笔",self.Model.pos_rate,str];
    }else{
        self.PosLabel01.text = [NSString stringWithFormat:@"%@%@/笔",self.Model.pos_rate,str];
    }
    
    if ([self.Model.pos_md isEqual:@"1"]) {
        self.MDLabel.hidden = NO;
    }else{
        self.MDLabel.hidden = YES;
    }
    CGFloat float01 = [self.Model.pos_rate floatValue] - [self.Model.pos_viprate floatValue];
    self.PosLabel02.text = [NSString stringWithFormat:@"%.2f%@",float01,str];
    CGFloat float02 = [self.Model.pos_rate floatValue] - [self.Model.pos_rrate floatValue];
    self.PosLabel03.text = [NSString stringWithFormat:@"%.2f%@",float02,str];
    self.PriceLabel.text = [NSString stringWithFormat:@"%@",self.Model.pos_price];
    self.PosYJPriceLabel.text = [NSString stringWithFormat:@"￥%@",self.Model.pos_price_deposit];
    self.YFPriceLabel.text = [NSString stringWithFormat:@"￥%@",self.Model.pos_price_freight];
    [self UpLoadOldAddress];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification1) name:@"alipaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification2) name:@"alipayFaild" object:nil];
    
    
    
    self.AllPriceLabel.text = [NSString stringWithFormat:@"%.2f",[self.Model.pos_price_deposit floatValue] * self.numb + [self.Model.pos_price_freight floatValue]+[self.Model.pos_price floatValue]];
}



- (void)UpLoadOldAddress{
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:KUserID forKey:@"address_member"];
    
    [MainObjectWay PostWithMethod:@"address_default" andAction:@"Pos" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"请求返回的信息 = %@",responseObject);
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                NSMutableDictionary * dic = responseObject[@"data"];
                self.AddressView01.hidden = YES;
                self.AddressView02.hidden = NO;
                self.AddressName.text = [NSString stringWithFormat:@"%@",dic[@"address_name"]];
                self.AddressiPhone.text = [NSString stringWithFormat:@"%@",dic[@"address_phone"]];
                self.AddressLabel.text = [NSString stringWithFormat:@"%@%@",dic[@"address_diqu"],dic[@"address_xx"]];
                self.AddressID = [NSString stringWithFormat:@"%@",dic[@"address_id"]];
            }else{
                self.AddressView01.hidden = NO;
                self.AddressView02.hidden = YES;
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"错误信息 = %@",error);
    }];
    
}

- (void)ClickOnBtnToLookLocationController{
    MyAddressController * AddressC = [[MyAddressController alloc] init];
    AddressC.delegate = self;
    [self.navigationController pushViewController:AddressC animated:YES];
}
- (IBAction)ClickOnBtnToAddLocationController:(id)sender {
    MyAddressController * AddressC = [[MyAddressController alloc] init];
    AddressC.delegate = self;
    [self.navigationController pushViewController:AddressC animated:YES];
}

- (void)ClickOnCellOfChooseAddressWithModel:(MyAddressModel *)model{
    self.AddressView01.hidden = YES;
    self.AddressView02.hidden = NO;
    MyAddressModel * model01 = model;
    
    self.AddressName.text = [NSString stringWithFormat:@"收货人：%@",model01.address_name];
    self.AddressiPhone.text = [NSString stringWithFormat:@"%@",model01.address_phone];
    self.AddressLabel.text = [NSString stringWithFormat:@"收货地址：%@%@",model01.address_diqu,model01.address_xx];
    self.AddressID = [NSString stringWithFormat:@"%@",model01.address_id];
}


- (IBAction)ClickOnBtnToAddNumber:(id)sender {
    self.numb++;
    self.numberButton.maxValue = MIN(self.maxQuanNum, self.numb);
    NSLog(@"::+%d",MIN(self.maxQuanNum, self.numb));
    self.PosNumbLabel.text = [NSString stringWithFormat:@"  %lu  ",(unsigned long)self.numb];
    
          float res = ([self.Model.pos_price_deposit floatValue] + [self.Model.pos_price floatValue]) * (self.numb - [self.quanNum floatValue]) + [self.Model.pos_price_freight floatValue];
    self.AllPriceLabel.text = [NSString stringWithFormat:@"%.2f",res];//[self.Model.pos_price_deposit floatValue] * self.numb + [self.Model.pos_price_freight floatValue]+[self.Model.pos_price floatValue]];
    
}

- (IBAction)ClickOnBtnToUpDownNumber:(id)sender {
    if (self.numb == 1) {
        return;
    }
    self.numb--;
    self.numberButton.maxValue = MIN(self.maxQuanNum, self.numb);;
    if(self.numb < [self.quanNum integerValue]){
        self.quanNum = [NSString stringWithFormat:@"%lu",(unsigned long)self.numb];
        self.numberButton.currentNumber = self.numb;
    }
    
    NSLog(@"::-%d",MIN(self.maxQuanNum, self.numb));
    self.PosNumbLabel.text = [NSString stringWithFormat:@"  %lu  ",(unsigned long)self.numb];
    
    float res = ([self.Model.pos_price_deposit floatValue] + [self.Model.pos_price floatValue]) * (self.numb - [self.quanNum floatValue]) + [self.Model.pos_price_freight floatValue];
    self.AllPriceLabel.text = [NSString stringWithFormat:@"%.2f",res];//[self.Model.pos_price_deposit floatValue] * self.numb + [self.Model.pos_price_freight floatValue]+[self.Model.pos_price floatValue]];
}

- (IBAction)ClickOnBtnToChangePayType:(id)sender {
    self.PayTypeBtn.selected = !self.PayTypeBtn.selected;
}



- (IBAction)ClickOnBtnToZhiFu:(id)sender {
    if ([KAddressID isEqual:nil]) {
        [MBProgressHUD showAlertViewWithText:@"请添加收货地址"];
        return;
    }
    
    if (self.AddressView01.hidden == NO) {
        [MBProgressHUD showAlertViewWithText:@"请添加收货地址"];
        return;
    }
    
    if (!self.PayTypeBtn.selected) {
        [MBProgressHUD showAlertViewWithText:@"请选择支付方式"];
        return;
    }
    
    
    self.hud = [MainObjectWay CreateHUDView:self.view];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.AddressID forKey:@"address_id"];
    [dic setObject:KUserID forKey:@"order_member"];
    [dic setObject:self.Model.pos_id forKey:@"order_pos"];
    [dic setObject:[NSString stringWithFormat:@"%lu",(unsigned long)self.numb] forKeyedSubscript:@"order_number"];
    [dic setObject:[NSString stringWithFormat:@"%lu",[self.quanNum integerValue]] forKey:@"order_deduction"];
    [dic setObject:self.AllPriceLabel.text forKeyedSubscript:@"order_amount"];
    [dic setObject:@"-----" forKey:@"order_desc"];
    
    [MainObjectWay PostWithMethod:@"create_order" andAction:@"Pos" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"提交订单返回数据 = %@",responseObject);
        [self.hud hideAnimated:YES];
        [MBProgressHUD showAlertViewWithText:responseObject[@"msg"]];
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            
            NSString * appScheme = @"2018041960010143";
            NSString * orderString = responseObject[@"data"];
            
            [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                NSLog(@"支付宝结果 === %@",resultDic);
                //回调在appDelegate
            }];
            
//            DYLQSuccessVC * vc = [[DYLQSuccessVC alloc]init];
//            vc.moneyStr = self.AllPriceLabel.text;
//            vc.orderStr = KUserID;
//            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSError *error) {
        [self.hud hideAnimated:YES];
        [MBProgressHUD showAlertViewWithText:@"订单提交失败"];
        NSLog(@"错误信息 = %@",error);
        [self notification2];
    }];
}

-(void)notification1{
    DYLQSuccessVC * vc = [[DYLQSuccessVC alloc]init];
    vc.moneyStr = self.AllPriceLabel.text;
    vc.orderStr = KUserID;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)notification2{
    DYLQFiledVC * vc = [[DYLQFiledVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)ClickLeftBarButtonItem{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)dealloc{
    //移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
